FDDeal = new Object();
// custom Vtype for vtype:'Rate'
Ext.apply(Ext.form.field.VTypes, {
	Rate : function(v) {
		return /^100(\.0{0,2})? *%?$|^\d{1,2}(\.\d{1,2})? *%?$/.test(v);
	},
	RateText : 'Invalid Rate',
	RateMask : /[\d\.%]/i
});

FDDeal.getSearchBar = function() {

	return Ext.create('Ext.form.FieldContainer', {
		items : [ {
			xtype : 'triggerfield',
			id : 'recFdTrigField',
			triggerCls : 'x-form-search-trigger',
			anchor : '28%',
			style : 'float:right;',
			emptyText : 'Search FDs',
			listeners : {
				specialkey : function(field, e) {
					if (e.getKey() == e.ENTER) {
						Ext.Msg.alert('HI', 'Press Enter');
					}
				}
			},
			onTriggerClick : function() {
				var searchResult = Ext.create('Ext.data.Store', {
					fields : [ 'id', 'dealCode', 'issuer', 'status' ]
				});
				var TrigField = Ext.ComponentQuery.query('#recFdTrigField')[0];

				Ext.Ajax.request({
					url : 'getFds.action',
					params : {
						queryOne : TrigField.getValue(),
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						var arrayLength = obj.deals.length;
						for (var i = 0; i < arrayLength; i++) {
							searchResult.add({
								id : obj.deals[i].id,
								dealCode : obj.deals[i].dealCode,
								issuer : obj.deals[i].issuer.code,
								name : obj.deals[i].name,
								status : obj.deals[i].status,
							});
						}
					}
				});

				var resultWindow = Ext.create('Ext.grid.Panel', {
					defaults : {
						anchor : '100%'
					},
					store : searchResult,
					columns : [ {
						text : 'Deal Code',
						dataIndex : 'dealCode',
						flex : 1
					}, {
						text : 'Issuer',
						dataIndex : 'issuer',
						flex : 1
					}, {
						text : 'Status',
						dataIndex : 'status',
						flex : 1
					} ],

					listeners : {
						itemclick : function(view, rec, item, index, eventObj) {
							var findId = rec.get('id');
							var formPanl = Ext.ComponentQuery.query('#recFdFormPanel')[0];
							var updateBtn = Ext.getCmp('recFdUpdateBtn');
							var saveBtn = Ext.getCmp('recFdSaveBtn');

							formPanl.getForm().reset();
							formPanl.setLoading('Receiving data...', formPanl.getForm());
							Ext.Ajax.request({
								url : 'getFd.action',
								params : {
									id : findId,
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);

									Ext.ComponentQuery.query('#recFdDealCode')[0].setText('Deal Code :' + obj.data.dealCode);
									Ext.ComponentQuery.query('#recFdDealStatus')[0].setText('Deal Status :' + obj.data.status);

									var valDtLocal = Ext.ComponentQuery.query('#recFdValueDt')[0];
									valDtLocal.format = 'd/m/Y';
									valDtLocal.setValue(obj.data.valueDate);

									var matDtLocal = Ext.ComponentQuery.query('#recFdMaturityDt')[0];
									matDtLocal.format = 'd/m/Y';
									matDtLocal.setValue(obj.data.valueDate);

									var tempFundCmb = Ext.ComponentQuery.query('#recFdFundCmb')[0];
									record = tempFundCmb.store.getById(obj.data.fund);
									tempFundCmb.select(obj.data.fund);
									tempFundCmb.fireEvent('select', tempFundCmb, record);

									var lblMaturityDate = Ext.ComponentQuery.query('#recFDDuration')[0];
									var durationDays = (matDtLocal.getValue() - valDtLocal.getValue()) / 86400000;
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));

									formPanl.getForm().load({
										url : 'getFd.action',
										params : {
											id : findId,
										},
										success : function(response) {
											formPanl.setLoading(false);
											FDDeal.setMatVal();
											if (rec.get('status') != 'Initial') {
												Ext.ComponentQuery.query('#recFdFundCmb')[0].disable();
												Ext.ComponentQuery.query('#recFdTrigField')[0].enable();
											}
											if (obj.data.withholdingTaxType === 'No') {
												Ext.ComponentQuery.query('#recFdWithholdRate')[0].disable();
												Ext.ComponentQuery.query('#recFdWithholdRate')[0].reset();
											} else {
												Ext.ComponentQuery.query('#recFdWithholdRate')[0].disable();
											}
										},
										failure : function(form, action) {
											formPanl.setLoading(false);
											Ext.Msg.alert("An Error occured. Load failed");
										}
									});

								},
								failure : function(form, action) {
									formPanl.setLoading(false);
								}
							});
							// If only viewing permissions
							if (rec.get('status') === 'Confirmed') {
								formPanl.getForm().getFields().each(function(field) {
									field.setDisabled(true);
								});
								Ext.getCmp('recFdWithholdRate').disable();
								saveBtn.disable();
								updateBtn.disable();
							} else {
								if (rec.get('status') === 'Initial') {
									formPanl.getForm().getFields().each(function(field) {
										field.setDisabled(false);
									});
									Ext.getCmp('outcomefieldSet').disable();
									Ext.getCmp('recFdWithholdRate').disable();
									saveBtn.disable();
									updateBtn.enable();
								} else {
									saveBtn.disable();
									updateBtn.disable();
								}
							}
							this.up('.window').close();
							Ext.ComponentQuery.query('#recFdTrigField')[0].enable();
						}
					}
				});

				Ext.create('Ext.window.Window', {
					title : 'FD Deals',
					id : 'recFdResWindow',
					height : 330,
					frame : true,
					width : 500,
					constrain : true,
					resizable : false,
					layout : {
						type : 'fit'
					},
					items : [ resultWindow ]
				}).show();

			}
		} ]
	});
};

FDDeal.getFieldSet1 = function() {
	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'fundName',
			type : 'string',
		}, {
			name : 'fundCode',
			type : 'string',
		} ],
		storeId : 'recFdFundStore',
	});

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'FD',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('recFdFundStore').loadRawData(obj.fundList);
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int',
		}, {
			name : 'name',
			type : 'string',
		}, {
			name : 'code',
			type : 'string',
		} ],
		storeId : 'recFdIssuerStore',
	});

	var selectFundComboBox = Ext.create('Ext.form.ComboBox', {
		id : 'recFdFundCmb',
		name : 'fund',
		fieldLabel : 'Fund',
		store : Ext.data.StoreManager.lookup('recFdFundStore'),
		flex : 1,
		padding : '0 10 0 0',
		labelWidth : 120,
		valueField : 'id',
		queryMode : 'local',
		autoScroll : true,
		allowBlank : false,
		msgTarget : 'under',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{fundName} - <b>{fundCode}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{fundName}', '</tpl>'),
		listeners : {
			change : function(list, record) {
				Ext.ComponentQuery.query('#recFdIssuer')[0].clearValue();
				Ext.data.StoreManager.lookup('recFdIssuerStore').removeAll();
				Ext.Ajax.request({
					url : 'getFdIssuers.action',
					params : {
						id : list.getValue()
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						Ext.data.StoreManager.lookup('recFdIssuerStore').loadRawData(obj.issuerList);
					},
					failure : function(response) {
						Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
					}
				});
			}
		},
		listConfig : {
			listeners : {
				itemclick : function(list, record) {
					Ext.ComponentQuery.query('#recFdIssuer')[0].clearValue();
					Ext.data.StoreManager.lookup('recFdIssuerStore').removeAll();
					Ext.Ajax.request({
						url : 'getFdIssuers.action',
						params : {
							id : record.get('id'),
						},
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							Ext.data.StoreManager.lookup('recFdIssuerStore').loadRawData(obj.issuerList);
						},
						failure : function(response) {
							Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
						}
					});
				}
			}
		}

	// *** Malsha

	// listeners : {
	// select : {
	// fn : function(combo, value) {
	// console.log(combo.getValue());
	// Ext.ComponentQuery.query('#recFdIssuer')[0].clearValue();
	// console.log(combo.getValue());
	// Ext.data.StoreManager.lookup('recFdIssuerStore').removeAll();
	// console.log(combo.getValue());
	// Ext.Ajax.request({
	// url : 'getFdIssuers.action',
	// params : {
	// id : combo.getValue(),
	// },
	// success : function(response) {
	// var obj = Ext.decode(response.responseText);
	// Ext.data.StoreManager.lookup('recFdIssuerStore').loadRawData(obj.issuerList);
	// },
	// failure : function(response) {
	// Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
	// }
	// });
	// }
	// }
	// }
	});

	var selectIssuerComboBox = Ext.create('Ext.form.ComboBox', {
		id : 'recFdIssuer',
		name : 'issuer',
		fieldLabel : 'Issuer',
		store : Ext.data.StoreManager.lookup('recFdIssuerStore'),
		valueField : 'id',
		queryMode : 'local',
		autoScroll : true,
		allowBlank : false,
		blankText : 'Please select an Issuer to proceed',
		msgTarget : 'under',
		flex : 1,
		padding : '0 5 0 0',
		// style : 'margin-top:10px;',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name} - <b>{code}</b><br/></div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),
	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			labelWidth : 175,
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'recFdDealCode',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ selectFundComboBox, selectIssuerComboBox ]
		}, {
			xtype : 'label',
			id : 'recFdDealStatus',
			style : 'font-weight:600;margin-top:7px;',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Value Date',
				name : 'valueDate',
				id : 'recFdValueDt',
				flex : 1,
				labelWidth : 120,
				padding : '0 10 0 0',
				style : 'margin-top:5px;',
				allowBlank : false,
				blankText : 'Please enter a Start Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					change : {
						fn : function(field, newVal, oldVal) {
							var dfMaturityDate = Ext.ComponentQuery.query('#recFdMaturityDt')[0];
							if (dfMaturityDate.getValue() != null) {
								var lblMaturityDate = Ext.ComponentQuery.query('#recFDDuration')[0];
								if (this.getValue() > dfMaturityDate.getValue()) {
									Ext.MessageBox.alert('Error', 'Value Date cannot be greater than Maturity Date.');
									this.setValue(null);
									lblMaturityDate.setText('');
								} else {
									var durationDays = (dfMaturityDate.getValue() - this.getValue()) / 86400000;
									lblMaturityDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									FDDeal.setMatVal();
								}
							}
						}
					}
				}
			}, {
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				name : 'maturityDate',
				id : 'recFdMaturityDt',
				allowBlank : false,
				flex : 1,
				padding : '0 5 0 0',
				style : 'margin-top:5px;',
				blankText : 'Please enter a Maturity Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'dd/mm/yyyy',
				minValue : new Date(),
				listeners : {
					change : {
						fn : function(field, newVal, oldVal) {
							var dfValueDate = Ext.ComponentQuery.query('#recFdValueDt')[0];
							if (dfValueDate.getValue() != null) {
								var lblValueDate = Ext.ComponentQuery.query('#recFDDuration')[0];
								if (dfValueDate.getValue() > this.getValue()) {
									Ext.MessageBox.alert('Error', 'Maturity Date cannot be smaller than Value Date.');
									this.setValue(null);
									lblValueDate.setText('');
								} else {
									var durationDays = (this.getValue() - dfValueDate.getValue()) / 86400000;
									lblValueDate.setText('Duration: '.concat(durationDays.toString().concat(' days.')));
									FDDeal.setMatVal();
								}
							}
						}
					}
				}

			} ]
		}, {
			xtype : 'label',
			id : 'recFDDuration',
		}, {
			xtype : 'label',
			id : 'recFdParamLbl',
			hidden : true,
			text : '',
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'radiogroup',
				fieldLabel : 'Withholding Tax',
				columns : 4,
				flex : 1,
				labelWidth : 120,
				vertical : true,
				items : [ {
					boxLabel : 'No',
					name : 'withholdingTaxType',
					inputValue : 'No',
					checked : true,
					id : 'recFdWithholdNoRB',
					listeners : {
						change : {
							fn : function(object, newVal, oldVal) {
								var tfwhtRate = Ext.ComponentQuery.query('#recFdWithholdRate')[0];
								if (newVal) {
									FDDeal.setMatValR('No');
									tfwhtRate.reset();
									tfwhtRate.disable();
								} else {
									tfwhtRate.enable();
								}
							}
						}
					}
				}, {
					boxLabel : 'Upfront',
					name : 'withholdingTaxType',
					inputValue : 'Upfront',
					id : 'recFdWithholdUpRB',
					listeners : {
						change : {
							fn : function(object, newVal, oldVal) {
								if (newVal) {
									FDDeal.setMatValR('Upfront');
								}
							}
						}
					}
				}, {
					boxLabel : 'Maturity',
					name : 'withholdingTaxType',
					inputValue : 'Maturity',
					id : 'recFdWithholdMatRB',
					listeners : {
						change : {
							fn : function(object, newVal, oldVal) {
								if (newVal) {
									FDDeal.setMatValR('Maturity');
								}
							}
						}
					}
				} ]
			}, {
				xtype : 'textfield',
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				allowBlank : false,
				disabled : true,
				flex : 0.5,
				name : 'withholdingTaxRate',
				id : 'recFdWithholdRate',
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						FDDeal.setMatVal();
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Delevary Method',
				store : CommenStore.delevaryMethodStore,
				valueField : 'id',
				flex : 1,
				labelWidth : 120,
				name : 'delevarymethode',
				padding : '0 10 0 0',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Dealer',
				store : CommenStore.dealersStore,
				valueField : 'id',
				flex : 1,
				padding : '0 5 0 0',
				name : 'dealerCode',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{name}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			} ]
		}, {
			xtype : 'combo',
			labelWidth : 120,
			fieldLabel : 'Settlement Method',
			store : CommenStore.settlmentStore,
			valueField : 'id',
			anchor : '50%',
			name : 'settlementCode',
			padding : '0 10 0 0',
			displayField : 'code',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
			listeners : {
				change : function(combo, record, index) {
					if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
						combo.setValue(null);
					}
				}
			}
		} ]
	});
	return finalFieldSet;
};

FDDeal.getFieldSet2 = function() {
	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Parameters',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				minValue : 0,
				name : 'principleValue',
				padding : '0 10 0 0',
				allowBlank : false,
				id : 'recFdPrincipleVal',
				fieldLabel : 'Principle Value',
				flex : 1,
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.00'));
						FDDeal.setMatVal();
					},
				}
			}, {
				xtype : 'textfield',
				name : 'actualRate',
				allowBlank : false,
				vtype : 'Rate',
				validateOnBlur : true,
				maskRe : /[\d\%.]/,
				fieldLabel : 'Actual Rate',
				flex : 0.5,
				labelWidth : 80,
				padding : '0 10 0 0',
				id : 'recFdActRate',
				listeners : {
					blur : function() {
						var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
						this.setRawValue(value + "%");
						FDDeal.setMatVal();
					}
				}
			}, {
				xtype : 'numberfield',
				minValue : 0,
				name : 'icp',
				labelWidth : 80,
				decimalPrecision : 0,
				allowBlank : false,
				id : 'recFdIcp',
				fieldLabel : 'ICP',
				value : 0,
				flex : 0.5,
				listeners : {
					render : function(p) {
						var theElem = p.getEl();
						var theTip = Ext.create('Ext.tip.Tip', {
							html : 'Interest Compound Period (in Months)',
							margin : '20 0 0 0',
							shadow : false
						});

						p.getEl().on('mouseover', function() {
							theTip.showAt(theElem.getX(), theElem.getY());
						});

						p.getEl().on('mouseleave', function() {
							theTip.hide();
						});
					},
					blur : function() {
						FDDeal.setMatVal();
					}
				}
			} ]
		} ]
	});
	return finalFieldSet;
};

FDDeal.getFieldSet3 = function() {

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Outcome',
		id : 'outcomefieldSet',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				id : 'recFdFaceValue',
				fieldLabel : 'Face Value',
				flex : 1,
				padding : '0 5 0 0',
				disabled : true,
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				id : 'recFdWithholdingTax',
				xtype : 'textfield',
				fieldLabel : 'Withholding Tax',
				disabled : true,
				flex : 1,
				padding : '0 5 0 0',
			}, {
				id : 'recFdEffRate',
				xtype : 'numberfield',
				maxValue : 100,
				fieldLabel : 'Effective Rate',
				flex : 1,
				padding : '0 5 0 0',
				disabled : true
			} ]
		} ]
	});
	return finalFieldSet;
};

FDDeal.getCenterPanel = function() {
	var searchBar = FDDeal.getSearchBar();
	var filedset1 = FDDeal.getFieldSet1();
	var filedset2 = FDDeal.getFieldSet2();
	var filedset3 = FDDeal.getFieldSet3();

	CommenStore.settlmentStore.load();
	CommenStore.dealersStore.load();
	CommenStore.delevaryMethodStore.load();

	var formPanel = Ext.create('Ext.form.FormPanel', {
		id : 'recFdFormPanel',
		bodyPadding : '20',
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 175,
			anchor : '68%',
		},
		fieldDefaults : {
			labelAlign : 'left',
			labelWidth : 150,
		},
		title : 'Record Fixed Deposite',
		items : [ searchBar, filedset1, filedset2, filedset3 ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();

				this.up('form').getForm().getFields().each(function(field) {
					field.setDisabled(false);
				});

				Ext.getCmp('recFdWithholdRate').disable();

				Ext.getCmp('outcomefieldSet').disable();
				Ext.ComponentQuery.query('#recFDDuration')[0].setText('');
				Ext.ComponentQuery.query('#recFdDealCode')[0].setText('');
				Ext.ComponentQuery.query('#recFdDealStatus')[0].setText('');
				(Ext.ComponentQuery.query('#recFdParamLbl')[0]).setText('');
				Ext.getCmp('recFdSaveBtn').enable();
				Ext.getCmp('recFdUpdateBtn').disable();
				// App.Core.setScreen(FDDeal.getCenterPanel());
			}
		}, {
			text : 'Save',
			id : 'recFdSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'newFd.action';
				if (form.isValid()) {
					formPanel.setLoading('Saving...');
					var valueDtField = Ext.ComponentQuery.query('#recFdValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#recFdMaturityDt')[0];
					var params = (Ext.ComponentQuery.query('#recFdParamLbl')[0]).text;
					form.submit({
						params : {
							'user' : 'createdUser',
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'params' : params,
						},
						success : function(form, action) {
							form.reset();
							Ext.Msg.alert('Success', 'Fixed Deposite created.<br> Deal Code is <b>' + action.result.dealCode + '</b>');
							Ext.ComponentQuery.query('#recFDDuration')[0].setText('');
							Ext.ComponentQuery.query('#recFdDealCode')[0].setText('');
							Ext.ComponentQuery.query('#recFdDealStatus')[0].setText('');
							(Ext.ComponentQuery.query('#recFdParamLbl')[0]).setText('');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>' + action.result.status);
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}
		}, {
			text : 'Update',
			id : 'recFdUpdateBtn',
			itemId : 'updateButton',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'modifyFd.action';
				Ext.ComponentQuery.query('#recFdFundCmb')[0].enable();

				if (form.isValid()) {

					formPanel.setLoading('Updating...');
					var valueDtField = Ext.ComponentQuery.query('#recFdValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#recFdMaturityDt')[0];
					var dealCode = Ext.ComponentQuery.query('#recFdDealCode')[0].text.substr(11);
					var params = (Ext.ComponentQuery.query('#recFdParamLbl')[0]).text;

					form.submit({
						params : {
							'user' : 'updatedUser',
							'dealCode' : dealCode,
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'params' : params,

						},
						success : function(form, action) {
							form.reset();
							Ext.ComponentQuery.query('#recFDDuration')[0].setText('');
							Ext.ComponentQuery.query('#recFdDealCode')[0].setText('');
							Ext.ComponentQuery.query('#recFdDealStatus')[0].setText('');
							(Ext.ComponentQuery.query('#recFdParamLbl')[0]).setText('');
							Ext.Msg.alert('Success', 'Deal is Updated.<br> Deal Code <b>' + action.result.dealCode + '</b>');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
							formPanel.setLoading(false);
						}
					});

				} else {
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}
		} ]
	});

	return formPanel;
};

FDDeal.setMatValR = function(withholdingTaxType) {

	var withholdingTaxRate = 0;
	if (withholdingTaxType == null || withholdingTaxType == '') {
		return;
	}
	var valueDt = Ext.ComponentQuery.query('#recFdValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#recFdMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	if (withholdingTaxType == 'Maturity' || withholdingTaxType == 'Upfront') {
		withholdingTaxRate = Ext.ComponentQuery.query('#recFdWithholdRate')[0].getValue().replace(/%/g, '');
		if (withholdingTaxRate == null || withholdingTaxRate == '')
			return;
	} else {
		withholdingTaxRate = "0.00";
	}

	var principleValue = Ext.ComponentQuery.query('#recFdPrincipleVal')[0].getValue();
	if (principleValue == '' || principleValue == null)
		return;

	var icp = Ext.ComponentQuery.query('#recFdIcp')[0].getValue();
	if (icp == null)
		return;

	var actualRate = Ext.ComponentQuery.query('#recFdActRate')[0].getValue().replace(/%/g, '');
	if (actualRate == null || actualRate == '')
		return;

	Ext.Ajax.request({
		url : 'evalFd.action',
		params : {
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'withholdingTaxType' : withholdingTaxType,
			'withholdingTaxRate' : withholdingTaxRate,
			'principleValue' : principleValue,
			'icp' : icp,
			'actualRate' : actualRate,
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#recFdFaceValue')[0].setValue(obj.maturityValue);
			Ext.ComponentQuery.query('#recFdWithholdingTax')[0].setValue(obj.withholdingTax);
			Ext.ComponentQuery.query('#recFdEffRate')[0].setValue(obj.rate);
		},
		failure : function(response) {
			Ext.ComponentQuery.query('#recFdFaceValue')[0].setValue('Error :' + obj.status);
		},
	});
};

FDDeal.setMatVal = function() {

	var valueDt = Ext.ComponentQuery.query('#recFdValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#recFdMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	var withholdingTaxType = Ext.ComponentQuery.query('#recFdWithholdNoRB')[0].getGroupValue();
	var withholdingTaxRate = Ext.ComponentQuery.query('#recFdWithholdRate')[0].getValue();
	if (withholdingTaxType == null || withholdingTaxType == '') {
		return;
	} else if (withholdingTaxType == 'Maturity' || withholdingTaxType == 'Upfront') {
		if (withholdingTaxRate == null)
			return;
	} else {
		withholdingTaxRate = "0";
	}

	var principleValue = Ext.ComponentQuery.query('#recFdPrincipleVal')[0].getValue();
	if (principleValue == '' || principleValue == null)
		return;

	var icp = Ext.ComponentQuery.query('#recFdIcp')[0].getValue();
	if (icp == null)
		return;

	var actualRate = Ext.ComponentQuery.query('#recFdActRate')[0].getValue();
	if (actualRate == null || actualRate == '')
		return;

	Ext.Ajax.request({
		url : 'evalFd.action',
		params : {
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'withholdingTaxType' : withholdingTaxType,
			'withholdingTaxRate' : withholdingTaxRate,
			'principleValue' : principleValue,
			'icp' : icp,
			'actualRate' : actualRate,
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#recFdFaceValue')[0].setValue(obj.maturityValue);
			Ext.ComponentQuery.query('#recFdWithholdingTax')[0].setValue(obj.withholdingTax);
			Ext.ComponentQuery.query('#recFdEffRate')[0].setValue(obj.rate);
		},
		failure : function(response) {
			Ext.ComponentQuery.query('#recFdFaceValue')[0].setValue('Error :' + obj.status);
		},
	});
};

FDDeal.getRollOverDeal = function(fund, issuer, dealCode, valueDate, principaleValue) {
	var panel = FDDeal.getCenterPanel();

	var tmpFundStore = Ext.data.StoreManager.lookup('recFdFundStore');
	var tmpIssuerStore = Ext.data.StoreManager.lookup('recFdIssuerStore');

	var tmpIssuerCmb = Ext.getCmp('recFdIssuer');
	var fundCmb = Ext.getCmp('recFdFundCmb');
	var tmpValDt = Ext.getCmp('recFdValueDt');
	var tmpDealValue = Ext.getCmp('recFdPrincipleVal');
	var paramLabel = Ext.getCmp('recFdParamLbl');

	Ext.Ajax.request({
		url : 'getFundsForDeal.action',
		params : {
			querry : 'FD',
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tmpFundStore.loadRawData(obj.fundList);
			fundCmb.setValue(tmpFundStore.getAt(tmpFundStore.find('fundCode', fund)).get('id'));

			tmpIssuerStore.removeAll();
			Ext.Ajax.request({
				url : 'getFdIssuers.action',
				params : {
					id : fundCmb.getValue(),
				},
				success : function(response) {
					var obj = Ext.decode(response.responseText);
					tmpIssuerStore.loadRawData(obj.issuerList);
					tmpIssuerCmb.setValue(tmpIssuerStore.getAt(tmpIssuerStore.find('code', issuer)).get('id'));
				},
				failure : function(response) {
					Ext.Msg.alert('Error!', 'Failed to Load Issuers!');
				}
			});

		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to load Fund List : ' + response);
		},
	});

	tmpValDt.setValue(valueDate);
	tmpDealValue.setValue(principaleValue);
	paramLabel.setText(dealCode);

	return panel;
};
